﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

using ERPStore.Web.Html;
using ERPStore.Web.Extensions;
using ERPStore.Extensions;

using Owin;

namespace ERPStore.Web
{
	public class MvcApplication : System.Web.HttpApplication
	{
		static bool m_IsFirstRequest = true;
		static object m_Lock = new object();

		protected void Application_Start()
		{
			AreaRegistration.RegisterAllAreas();
			// ERPStoreStartup.Init(Context);
		}

		protected void Application_End()
		{
			var eventPublisher = GlobalConfiguration.Configuration.DependencyResolver.GetService<EventBrokR.IPublisher>();
			if (eventPublisher != null)
			{
				eventPublisher.PublishAsync(new ERPStore.Events.EndApplicationRequestedEvent()).Wait(2 * 1000);
			}
		}

		protected void Application_BeginRequest(object sender, EventArgs args)
		{
			if (m_IsFirstRequest)
			{
				lock (m_Lock)
				{
					if (m_IsFirstRequest)
					{
						ERPStoreStartup.Init(Context);
						m_IsFirstRequest = false;
					}
				}
			}


			if (GlobalConfiguration.Configuration.FailedOnInitialize)
			{
				if (!Context.Request.IsLocal)
				{
					Context.Response.Write("Failed on initialization, show event log for more informations");
					Context.Response.End();
				}
				else
				{
					Context.Response.Write(string.Format("{0}", GlobalConfiguration.Configuration.FirstError));
					Context.Response.End();
				}
			}

			if (GlobalConfiguration.Configuration.Shutdown)
			{
				var fileName = Context.Server.MapPath("~/shutdown.html");
				try
				{
					Context.Response.ContentType = "text/html";
					Context.Response.WriteFile(fileName);
				}
				catch
				{
				}
				Context.Response.End();
			}

		}

		protected void Application_Error(object sender, EventArgs e)
		{
			try
			{
				Logging.WebError.Handle(Context);
			}
			catch (Exception ex)
			{
				System.Diagnostics.EventLog.WriteEntry("Application", ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
			}
		}

		protected void Application_OnPostAuthenticateRequest(object sender, EventArgs args)
		{
			Web.Security.Authentication.AuthenticateRequest(Context);
		}

		public override string GetVaryByCustomString(HttpContext context, string custom)
		{
			var result = string.Empty;
			if (custom.IndexOf("IsAnonymous") != -1)
			{
				result += context.User.Identity.IsAuthenticated ? context.User.Identity.Name : "anon";
			}
			if (custom.IndexOf("Host") != -1)
			{
				result += context.Request.Url.Host;
			}
			return result;
		}

	}
}
